package com.acme.bankapp.service.email;

import com.acme.bankapp.domain.email.Queue;
import com.acme.bankapp.domain.email.Email;

public class EmailService implements Runnable {
	private static volatile EmailService instance = null;
	private static Object lock = new Object();
	Thread workerThread;
	
	public static EmailService getInstance() {
		EmailService result = instance;
		if (result == null) {
			synchronized(lock) {
				result = instance;
				if (result == null) {
					result = new EmailService();
				}
			}
		}
		return result;
	}
	
	
	private Queue queue = new Queue(10);
	
	private EmailService() {
		workerThread = new Thread(this);
		workerThread.start();
	}
	
	public void sendNotificationEmail(Email email) throws IllegalStateException {
		queue.putItem(email);
	}
	
	public void close() {
		queue.close();
		workerThread.interrupt();
	}

	@Override
	public void run() {
		Email email;
		while ((email = queue.getItem()) != null) {
			try {
				Thread.sleep(200); // pretend that sending takes some time
			} catch (InterruptedException ignore) { }
			System.out.printf("[MAILER] %s%n", email);
		}

	}
	
}
